package com.jucai.pppeiyouclient.view.activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.amap.api.maps2d.model.Text;
import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseTakePhotoActivity;
import com.jucai.pppeiyouclient.base.PermissionListener;
import com.jucai.pppeiyouclient.comm.CommonData;
import com.jucai.pppeiyouclient.comm.CommonMethod;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.CompressPhoto;
import com.jucai.pppeiyouclient.utils.ImageHandleUtils;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.OssUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.popup.EduChoosePopup;
import com.jucai.pppeiyouclient.view.popup.HeadUploadPopup;
import com.jucai.pppeiyouclient.view.popup.SexChoosePopup;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


public class RegisterSecondStepActivity extends BaseTakePhotoActivity {
    private static final String TAG = "RegisterSecondStepActivity : ";
    private static final int TAKE_PHOTO = 2001;
    private static final int CHOOSE_IMAGE = 2002;
    private static final int CROP_IMAGE = 2003;
    private static final int GET_CITY = 3001;

    private CircleImageView registerHeadUp;
    private EditText registerName, registerCareer, registerAge, registerDesc;
    private TextView registerSex, registerBorn, registerEdu, registerCity, registerNext2;
    private HeadUploadPopup headUploadPopup;
    private SexChoosePopup sexChoosePopup;
    private EduChoosePopup eduChoosePopup;
    private String cityId;
    private String isEmpty;
    private String objectKey;
    private String registerEduCode;
    private boolean avatarBoolean;
    private boolean isImageUploading = false;

    /**
     * 照片存储文件夹
     */
    private File imageStore = null;


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_register_second_step);

        ((TextView) findViewById(R.id.common_title_text)).setText("注册");
        findViewById(R.id.common_home_back).setVisibility(View.INVISIBLE);
        registerHeadUp = (CircleImageView) findViewById(R.id.register_head_up);
        registerName = (EditText) findViewById(R.id.register_name);
        registerAge = (EditText) findViewById(R.id.register_age);
        registerDesc = (EditText) findViewById(R.id.register_desc);
        registerCareer = (EditText) findViewById(R.id.register_career);
        registerCity = (TextView) findViewById(R.id.register_city);
        registerSex = (TextView) findViewById(R.id.register_sex);
        registerBorn = (TextView) findViewById(R.id.register_born);
        registerEdu = (TextView) findViewById(R.id.register_edu);
        registerNext2 = (TextView) findViewById(R.id.register_next_2);
    }

    private void getIntentInfo(){
        Intent i = getIntent();
        if(i.hasExtra("extra_member_avatar")){
            avatarBoolean = true;
            String temp = i.getStringExtra("extra_member_avatar");
            Glide.with(this)
                    .load(temp)
                    .centerCrop()
                    .override(120, 120)
                    .error(R.drawable.register_icon_head_default)
                    .into(registerHeadUp);
        }
        if(i.hasExtra("extra_member_sexual")){
            String temp = i.getStringExtra("extra_member_sexual");
            if(TextUtils.equals(temp,"1")){
                registerSex.setText("男");
            }else if(TextUtils.equals(temp,"2")){
                registerSex.setText("女");
            }else{
                registerSex.setText("");
            }
        }
        if(i.hasExtra("extra_member_age")){
            String temp = i.getStringExtra("extra_member_age");
            registerAge.setText(temp);
        }
        if(i.hasExtra("extra_member_education")){
            String temp = i.getStringExtra("extra_member_education");
            if(TextUtils.equals(temp,"6")){
                registerEdu.setText("博士");
            }else if(TextUtils.equals(temp,"5")){
                registerEdu.setText("硕士");
            }else if(TextUtils.equals(temp,"4")){
                registerEdu.setText("本科");
            }else if(TextUtils.equals(temp,"3")){
                registerEdu.setText("专科");
            }else if(TextUtils.equals(temp,"2")){
                registerEdu.setText("高中");
            }else if(TextUtils.equals(temp,"1")){
                registerEdu.setText("初中");
            }else{
                registerEdu.setText("不限");
            }
        }
        if(i.hasExtra("extra_member_occupation")){
            String temp = i.getStringExtra("extra_member_occupation");
            registerCareer.setText(temp);
        }
        if(i.hasExtra("extra_accompany_server_city")){
            String temp = i.getStringExtra("extra_accompany_server_city");
            registerCity.setText(temp);
        }
        if(i.hasExtra("extra_member_desc")){
            String temp = i.getStringExtra("extra_member_desc");
            registerDesc.setText(temp);
        }
    }

    @Override
    protected void configCompress(TakePhoto takePhoto) {
        int maxSize = 1 * 1024 * 1024;
        int width = 150;
        int height = 150;
        boolean showProgressBar = true;
        boolean enableRawFile = true;//保留原图
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(maxSize)
                .setMaxPixel(width >= height ? width : height)
                .enableReserveRaw(enableRawFile)
                .create();
        takePhoto.onEnableCompress(config, showProgressBar);
    }

    @Override
    protected void initData() {
        imageStore = new File(Environment.getExternalStorageDirectory(),
                CommonData.STORAGE_PHOTO + System.currentTimeMillis() + ".jpg");
        avatarBoolean = false;
        registerName.setSingleLine();
        registerCareer.setSingleLine();
        getIntentInfo();
        /**
         * 初始化 popup
         */
        headUploadPopup = new HeadUploadPopup(this, getWindow(), R.style.animBottomInBottomOut,
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        headUploadPopup.dismiss();
                        switch (view.getId()) {
                            case R.id.upload_photo:

                                if (Build.VERSION.SDK_INT >= 23) {
                                    RegisterSecondStepActivity.this
                                            .onRuntimePermissionRequest(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                                                    new PermissionListener() {
                                                        @Override
                                                        public void onGranted() {
                                                            ImageHandleUtils.takePhoto(RegisterSecondStepActivity.this, imageStore, TAKE_PHOTO);
                                                        }

                                                        @Override
                                                        public void onDenied(List<String> deniedPermissions) {
                                                            runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    ToastUtils.showToast("调起摄像头失败！");
                                                                }
                                                            });
                                                        }
                                                    });
                                } else
                                    ImageHandleUtils.takePhoto(RegisterSecondStepActivity.this, imageStore, TAKE_PHOTO);

                                break;
                            case R.id.upload_album:

                                getTakePhoto().onPickMultiple(1);
//                                if (Build.VERSION.SDK_INT >= 23) {
//                                    //写SD卡权限申请
//                                    BaseActivity.onRuntimePermissionRequest(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                                            new PermissionListener() {
//                                                @Override
//                                                public void onGranted() {
//                                                    ImageHandleUtils.openAlum(RegisterSecondStepActivity.this, CHOOSE_IMAGE);
//                                                }
//
//                                                @Override
//                                                public void onDenied(List<String> deniedPermissions) {
//                                                    for (String p : deniedPermissions) {
//                                                        Toast.makeText(ActivityCollector.getTopActivity(),
//                                                                p + "权限被拒绝", Toast.LENGTH_SHORT).show();
//                                                    }
//                                                }
//                                            });
//                                } else
//                                    ImageHandleUtils.openAlum(RegisterSecondStepActivity.this, CHOOSE_IMAGE);

                                break;

                            case R.id.upload_cancel:
                                headUploadPopup.dismiss();
                                break;
                            default:
                                break;
                        }
                    }
                });

        sexChoosePopup = new SexChoosePopup(this, getWindow(), R.style.animBottomInBottomOut, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sexChoosePopup.dismiss();
                switch (view.getId()) {
                    case R.id.popup_male:
                        registerSex.setText("男");
                        break;
                    case R.id.popup_female:
                        registerSex.setText("女");
                        break;
                    default:
                        break;
                }
            }
        });

        registerEdu.setText("不限");
        registerEduCode = "0";

        eduChoosePopup = new EduChoosePopup(this, getWindow(), R.style.animBottomInBottomOut, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                eduChoosePopup.dismiss();
                switch (view.getId()) {
                    case R.id.edu_doctor:
                        registerEdu.setText("博士");
                        registerEduCode = "6";
                        break;
                    case R.id.edu_master:
                        registerEdu.setText("硕士");
                        registerEduCode = "5";
                        break;
                    case R.id.edu_undergraduate:
                        registerEdu.setText("本科");
                        registerEduCode = "4";
                        break;
                    case R.id.edu_junior:
                        registerEdu.setText("专科");
                        registerEduCode = "3";
                        break;
                    case R.id.edu_high_school:
                        registerEdu.setText("高中");
                        registerEduCode = "2";
                        break;
                    case R.id.edu_middle_school:
                        registerEdu.setText("初中");
                        registerEduCode = "1";
                        break;
                    case R.id.edu_other:
                        registerEdu.setText("不限");
                        registerEduCode = "0";
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        registerHeadUp.setOnClickListener(this);
        registerSex.setOnClickListener(this);
        registerBorn.setOnClickListener(this);
        registerEdu.setOnClickListener(this);
        registerCity.setOnClickListener(this);
        registerNext2.setOnClickListener(this);
    }

    private String judgeEmpty() {
        /*
         else if (TextUtils.equals(registerBorn.getText().toString(), "请选择出生日期")) {
            return "请选择出生日期";
        }
         */
        if (!avatarBoolean) {
            return "请选择头像";
        } else if (TextUtils.isEmpty(registerName.getText().toString())) {
            return "姓名不能为空";
        } else if (TextUtils.equals(registerSex.getText().toString(), "请选择性别")) {
            return "请选择性别";
        } else if (TextUtils.equals(registerEdu.getText().toString(), "请选择学历")) {
            return "请选择学历";
        } else if (TextUtils.isEmpty(registerCareer.getText().toString())) {
            return "职业不能为空";
        } else if (TextUtils.equals(registerCity.getText().toString(), "请选择城市")) {
            return "请选择城市";
        } else if (TextUtils.isEmpty(registerAge.getText().toString())) {
            return "请输入年龄";
        } else if (Integer.valueOf(registerAge.getText().toString().trim())<18) {
            return "设置年龄必须大于18岁";
        } else if (TextUtils.isEmpty(registerDesc.getText().toString())) {
            return "请输入个人简介";
        } else {
            return "";
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    showCropImage(data);
                    break;
//                case CHOOSE_IMAGE:
//                    ImageHandleUtils.startCropImage(RegisterSecondStepActivity.this,
//                            data.getData(), CROP_IMAGE, 1, 1, 200, 200);
//                    break;
//                case CROP_IMAGE:
//                    if (data != null) {
//                        LogUtils.e(TAG + "after crop");
//                        showCropImage(data);
//                    }
//                    break;

                case GET_CITY:
                    String cityName = data.getStringExtra("city_name");
                    cityId = data.getStringExtra("city_id");
                    registerCity.setText(cityName);

                default:
                    break;
            }
        }
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        uploadImage(result.getImages());
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }


    private void uploadImage(ArrayList<TImage> images) {
        try {
            String photoPath = images.get(0).getCompressPath();
            if (TextUtils.isEmpty(photoPath))
                photoPath = images.get(0).getOriginalPath();

            objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
            OssUtils.uploadPic(photoPath, objectKey, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    avatarBoolean = true;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    objectKey = "";
                    ToastUtils.showToast("头像上传失败！请稍后再试");
                }
            },new OssUtils.onPhotoUploadResult(){
                @Override
                public void onResult(String key, String filePath) {

                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
            Glide.with(RegisterSecondStepActivity.this).load(photoPath).skipMemoryCache(true).error(R.drawable.register_icon_head_default).into(registerHeadUp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showCropImage(Intent data) {
        Glide.with(this).load(imageStore.getPath()).into(registerHeadUp);
        try {
            if (data != null && data.getExtras() != null) {
                Bundle extras = data.getExtras();
                Bitmap photo = extras.getParcelable("data");
                CompressPhoto.saveFile(photo, imageStore.getPath());
            }

            objectKey = "temp/" + System.currentTimeMillis() + ".jpg";
            OssUtils.uploadPic(imageStore.getPath(), objectKey, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                    avatarBoolean = true;
                }

                @Override
                public void onFailure(PutObjectRequest putObjectRequest, ClientException e, ServiceException e1) {
                    objectKey = "";
                    ToastUtils.showToast("头像上传失败！请稍后再试");
                }
            },new OssUtils.onPhotoUploadResult(){
                @Override
                public void onResult(String key, String filePath) {

                }

                @Override
                public void onProgress(long currentSize, long totalSize) {
                    if(currentSize >= totalSize){
                        isImageUploading = false;
                    }else{
                        isImageUploading = true;
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                break;
            case R.id.register_head_up:
                if(isImageUploading){
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                headUploadPopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.register_sex:
                sexChoosePopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.register_born:
                Calendar calendar = Calendar.getInstance();

                final int yearInt = calendar.get(Calendar.YEAR);
                final int monthInt = calendar.get(Calendar.MONTH) + 1;
                final int dayInt = calendar.get(Calendar.DAY_OF_MONTH);

                LogUtils.d(yearInt + "|" + monthInt + "|" + dayInt);

                new DatePickerDialog(RegisterSecondStepActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                        monthOfYear = monthOfYear + 1;
                        if (year > yearInt) {
                            ToastUtils.showToast("日期错误");
                            return;
                        }
                        if (year == yearInt) {
                            if (monthOfYear > monthInt) {
                                ToastUtils.showToast("日期错误");
                                return;
                            }
                            if (monthOfYear == monthInt) {
                                if (dayOfMonth > dayInt) {
                                    ToastUtils.showToast("日期错误");
                                    return;
                                }
                            }
                        }
                        String dayString = dayOfMonth + "";
                        String monthString = monthOfYear + "";
                        if (monthOfYear < 10) {
                            monthString = "0" + monthString;
                        }
                        if (dayOfMonth < 10) {
                            dayString = "0" + dayString;
                        }
                        registerBorn.setText(year + "-" + monthString + "-" + dayString);
                    }
                }, yearInt, monthInt - 1, dayInt).show();
                break;
            case R.id.register_edu:
                eduChoosePopup.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                CommonMethod.setWindowAlpha((float) 0.5, getWindow());
                break;

            case R.id.register_city:
                startActivityForResult(new Intent(RegisterSecondStepActivity.this, CitySelectActivity.class), GET_CITY);
                break;

            case R.id.register_next_2:
                if(isImageUploading){
                    ToastUtils.showToast("上传图片中，请稍后再试");
                    break;
                }
                isEmpty = judgeEmpty();
                if (TextUtils.equals(isEmpty, "")) {
                    int sexual = 0;
                    HashMap<String, String> param = new HashMap<>();
                    param.put("service", "Accompany_Info.updateUserInfo");
                    param.put("member_realname", registerName.getText().toString());
                    if (registerSex.getText().toString().equals("男")) {
                        sexual = 1;
                    } else if (registerSex.getText().toString().equals("女")) {
                        sexual = 2;
                    }
                    param.put("member_sexual", sexual + "");
                    //param.put("member_birth", registerBorn.getText().toString());
                    param.put("member_education", registerEduCode);
                    param.put("member_occupation", registerCareer.getText().toString());
                    param.put("member_age", registerAge.getText().toString());
                    param.put("member_desc", registerDesc.getText().toString());
                    param.put("member_city_id", cityId);
                    param.put("member_avatar", objectKey);
                    LogUtils.e(TAG + param.toString());

                    CommonRequestNetData.getJsonStringData(RegisterSecondStepActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
                        @Override
                        public void parseJsonString(String str) {
                            ToastUtils.showToast(str);
                            RegisterThirdStepActivity.startRealName(RegisterSecondStepActivity.this, 0);
                            finish();
                        }
                    });
                } else {
                    ToastUtils.showToast(isEmpty);
                }
                break;
            default:
                break;
        }
    }
}
